<!-- src\views\stats\MachineDetail.vue -->
<template>
  <div class="machine-detail">
    <h2>机器详细分析</h2>
    <el-form :model="filters" label-width="100px" class="filter-form">
      <el-form-item label="时间范围">
        <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item label="机器类别">
        <el-select v-model="filters.machineCategory" placeholder="请选择">
          <el-option label="所有" value="" />
          <el-option v-for="group in agriculturalMachines" :key="group.title" :label="group.title" :value="group.title" />
        </el-select>
      </el-form-item>
      <el-form-item label="机器名称">
        <el-input v-model="filters.machineName" placeholder="输入机器名称" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="applyFilters">查询</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="charts">
      <div id="usage-chart" style="width: 100%; height: 400px;"></div>
      <div id="failure-chart" style="width: 100%; height: 400px;"></div>
    </div>
    <el-table :data="machineStore.machines" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="机器名称" />
      <el-table-column prop="type" label="类型" />
      <el-table-column prop="status" label="状态" />
      <el-table-column prop="usageCount" label="使用次数" />
    </el-table>
    <el-button type="primary" @click="compareMachines" :disabled="selectedMachines.length !== 2">对比选中机器</el-button>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';
import { useMachineStore } from '@/stores/machine';
import { useAgriculturalDataStore } from '@/stores/agriculturalData';

const machineStore = useMachineStore();
const agriculturalDataStore = useAgriculturalDataStore();
const filters = ref(machineStore.filters);
const dateRange = ref<[Date, Date] | null>(null);
const selectedMachines = ref<any[]>([]);
const agriculturalMachines = agriculturalDataStore.getAgriculturalMachines;

const applyFilters = async () => {
  if (dateRange.value) {
    filters.value.startDate = dateRange.value[0].toISOString().split('T')[0];
    filters.value.endDate = dateRange.value[1].toISOString().split('T')[0];
  }
  machineStore.setFilters(filters.value);
  await Promise.all([machineStore.fetchStatistics(), machineStore.fetchMachines()]);
  renderCharts();
};

const resetFilters = () => {
  dateRange.value = null;
  machineStore.clearFilters();
  filters.value = machineStore.filters;
  applyFilters();
};

const handleSelectionChange = (val: any[]) => {
  selectedMachines.value = val;
};

const compareMachines = () => {
  ElMessage.info(`对比 ${selectedMachines.value[0].name} 和 ${selectedMachines.value[1].name}`);
  // 这里可以跳转到对比页面或弹窗展示对比结果
};

const renderCharts = () => {
  const usageChart = echarts.init(document.getElementById('usage-chart') as HTMLElement);
  usageChart.setOption({
    title: { text: '机器使用频率' },
    tooltip: {},
    xAxis: { type: 'category', data: machineStore.statistics.usageFrequency.map(item => item.date) },
    yAxis: { type: 'value' },
    series: [{
      name: '使用次数',
      type: 'line',
      data: machineStore.statistics.usageFrequency.map(item => item.count),
    }],
  });

  const failureChart = echarts.init(document.getElementById('failure-chart') as HTMLElement);
  failureChart.setOption({
    title: { text: '机器故障率' },
    tooltip: {},
    xAxis: { type: 'category', data: machineStore.statistics.failureRate.map(item => item.name) },
    yAxis: { type: 'value' },
    series: [{
      name: '故障次数',
      type: 'bar',
      data: machineStore.statistics.failureRate.map(item => item.value),
    }],
  });
};

onMounted(applyFilters);
</script>

<style scoped>
.machine-detail {
  padding: 20px;
}
.filter-form {
  margin: 0px 400px 50px 400px;
}
.charts {
  margin-bottom: 40px;
}
</style>